package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import dao.UserDao;
import pojo.User;
import util.DBUtil;

	public class UserDaoImpl implements UserDao {

		public int addUser(User u) {
			String sql = "insert into users(id,name,salary,birth,sex) values(seq_05.nextval,?,?,?,?)";
			Connection con=null;
			PreparedStatement pst = null;
			int m = 0;
			try {
				con=DBUtil.createConnection();
				pst = con.prepareStatement(sql);
				pst.setString(1, u.getName());
				pst.setDouble(2, u.getSalary());
				pst.setDate(3, new java.sql.Date(u.getBirth().getTime()));
				pst.setBoolean(4, u.isSex());
				
				m = pst.executeUpdate();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				DBUtil.close(null, pst, null);
			}
			return m;
		}


		public List<User> findAll() {
			List<User> list=new ArrayList<User>();
			String sql = "select * from users";
			Connection con=null;
			PreparedStatement pst = null;
			ResultSet rs =null;
			try {
				con=DBUtil.createConnection();
				pst = con.prepareStatement(sql);
				
				rs = pst.executeQuery();
				while (rs.next()) {
					User u=new User();
					u.setId(rs.getInt(1));
					String name = rs.getString("name");
					double sal = rs.getDouble("salary");
					Date birth = new Date(rs.getDate("birth").getTime());
					boolean sex = rs.getBoolean("sex");
					
					u.setName(name);
					u.setBirth(birth);
					u.setSex(sex);
					u.setSalary(sal);
					list.add(u);
					
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			finally{
				DBUtil.close(null, pst, rs);
			}
			return list;
		}

	}
